import React, { ReactElement, useState, useEffect, useRef } from 'react';
import { Animated } from 'react-native';
import WebView from 'react-native-webview';
import X5WebView from 'react-native-webview-x5';
import { WebViewProgressEvent } from 'react-native-webview/lib/WebViewTypes';
import createInvoke, { IMessager } from 'react-native-webview-invoke/native';

import styles from './style';
import { getScreenInfo } from '../../util/screen';
import Provider from './reducer';
import { isIOS } from '../../constant';
import {
  editProblem,
  selectPic,
  setOnAudioUploaded,
  setShowRecord,
  updateAudio
} from './actions';
import Record from './components/Record';
import Log from '../../common/log';
import navigator from '../../util/navigator';

const { width } = getScreenInfo({});

const TAG = 'Correction';

export default (): ReactElement => {
  const webView = useRef<WebView>(null);
  const invoke: IMessager = createInvoke((): any =>
    webView && webView.current
      ? webView.current
      : {
          postMessage: (data: any): void => {}
        }
  );

  const [progress, setProgress] = useState(0);

  const [progressWidth] = useState(new Animated.Value(0));
  const [progressOpacity] = useState(new Animated.Value(1));

  // 调用WebView提供的函数
  const setCorrectionInfoInRN = invoke.bind('setCorrectionInfoInRN');
  const confirmEditProblemInRN = invoke.bind('confirmEditProblemInRN');
  const confirmUpdateAudioInRN = invoke.bind('confirmUpdateAudioInRN');
  const selectImageInRN = invoke.bind('selectImageInRN');
  const setAudioInRN = invoke.bind('setAudioInRN');

  setOnAudioUploaded(setAudioInRN);

  // 提供函数供WebView调用
  // 同步做题记录（做题时间也要同步？）
  const syncCorrectionInWebview = (value: any): void => {
    // TODO: 存缓存
    Log.i(TAG, 'syncCorrectionInWebview');
  };
  // 呼出修改练习题弹窗
  const openEditProblemInWebview = (): void => {
    editProblem(confirmEditProblemInRN);
    Log.i(TAG, 'openEditProblemInWebview');
  };
  // 呼出更新语音弹窗
  const openUpdateAudioInWebview = (): void => {
    updateAudio(confirmUpdateAudioInRN);
    Log.i(TAG, 'openUpdateAudioInWebview');
  };
  // 提交作业
  const submitCorrectionInWebview = (): void => {
    // TODO: 提交作业+提交成功回调
    Log.i(TAG, 'submitCorrectionInWebview');
  };
  // 打开上传图片弹窗
  const openSelectImageInWebview = (): void => {
    selectPic(selectImageInRN);
    Log.i(TAG, 'openSelectImageInWebview');
  };
  // 打开录音弹窗
  const openRecordAudioInWebview = (): void => {
    setShowRecord(true);
    Log.i(TAG, 'openRecordAudioInWebview');
  };
  // 返回
  const goBackInWebview = (): void => {
    navigator.goBack();
    Log.i(TAG, 'goBackInWebview');
  };
  invoke.define('syncCorrectionInWebview', syncCorrectionInWebview);
  invoke.define('openEditProblemInWebview', openEditProblemInWebview);
  invoke.define('openUpdateAudioInWebview', openUpdateAudioInWebview);
  invoke.define('submitCorrectionInWebview', submitCorrectionInWebview);
  invoke.define('openSelectImageInWebview', openSelectImageInWebview);
  invoke.define('openRecordAudioInWebview', openRecordAudioInWebview);
  invoke.define('goBackInWebview', goBackInWebview);

  useEffect((): void => {
    Animated.timing(progressWidth, {
      toValue: progress * width,
      duration: 800
    }).start();
  }, [progress, progressWidth]);

  useEffect((): void => {
    if (progress === 1) {
      setTimeout((): void => {
        Animated.timing(progressOpacity, {
          toValue: 0,
          duration: 400
        }).start();
      }, 500);
    }
  }, [progress, progressOpacity]);

  // useEffect((): void => {
  //   setTimeout((): void => {
  //     setShowRecord(true);
  //   }, 1000);
  // }, []);

  return (
    <Provider>
      <Animated.View
        style={[
          styles.progress,
          {
            width: progressWidth,
            opacity: progressOpacity
          }
        ]}
      />
      {isIOS ? (
        <WebView
          ref={webView}
          style={styles.webView}
          source={{
            uri: 'http://baidu.com'
          }}
          onLoadProgress={(e: WebViewProgressEvent): void => {
            setProgress(e.nativeEvent.progress);
          }}
          onError={(): void => {}}
          onMessage={invoke.listener}
        />
      ) : (
        <X5WebView
          ref={webView}
          style={styles.webView}
          source={{
            uri: 'http://192.168.50.151:4000/aikidCorrection/'
          }}
          androidLayerType="software"
          onLoadProgress={(e: WebViewProgressEvent): void => {
            setProgress(e.nativeEvent.progress);
          }}
          onError={(): void => {}}
          onMessage={invoke.listener}
        />
      )}
      <Record />
    </Provider>
  );
};
